package my.suveng.alarm.de;

import com.alibaba.fastjson.JSON;
import my.suveng.alarm.config.AlarmProperties;
import my.suveng.alarm.dependency.Message;
import my.suveng.alarm.dependency.Notify;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;

/**
 * @author suwenguang
 * @date 2020/11/8 3:20 下午
 * @since 1.0
 */
public class DingNotify implements Notify {

    private static final Logger log = LoggerFactory.getLogger(DingNotify.class);

    private final AlarmProperties properties;

    public DingNotify(AlarmProperties properties) {
        this.properties = properties;
    }

    @Override
    public void send(Message message) {
        RestTemplate restTemplate = getRestTemplate(properties.getRestConnectTimeout(), properties.getRestReadTimeout());
        String url = properties.getDingRoboLink();

        HttpHeaders headers = fillHeader();

        DingTalkRequest params = fillParam(message.beautiful());

        try {
            HttpEntity<String> requestEntity = new HttpEntity<>(JSON.toJSONString(params),
                    headers);
            restTemplate.postForEntity(url, requestEntity, String.class);
        } catch (Exception e) {
            log.error("发送钉钉消息失败", e);
        }
    }

    /**
     * 填充header信息
     * @return {@link HttpHeaders}
     */
    private HttpHeaders fillHeader() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return headers;
    }

    /**
     * 填充参数
     * @param message 消息
     * @return  {@link DingTalkRequest}
     */
    private DingTalkRequest fillParam(String message) {
        DingTalkRequest params = new DingTalkRequest();
        params.setMsgtype("text");
        DingTalkRequest.Text text = new DingTalkRequest.Text();
        text.setContent(message);
        params.setText(text);
        DingTalkRequest.At at = new DingTalkRequest.At();
        at.setIsAtAll(false);
        at.setAtMobiles(properties.getPhones());
        params.setAt(at);
        return params;
    }

    private RestTemplate getRestTemplate(int connectTimeout, int readTimeout) {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(connectTimeout);
        requestFactory.setReadTimeout(readTimeout);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        ArrayList<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
        interceptors.add(new TrackRestTemplateInterceptor());
        restTemplate.setInterceptors(interceptors);
        return restTemplate;
    }
}
